import { SERVICES } from '@/common';
import FormCommon from '@/components/FormCommon';
import moment from 'moment';
import AvatarCom from '@/components/avatarUpload';
import CommonTable from '@/components/commonTable';
import { IFilterParams } from '@/components/commonTable/interface';
import { add, deleted, getCurrent, update } from '@/services/api/service';
import { DrawerForm, PageContainer, ProForm, ProFormText } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { useRequest } from 'ahooks-v3';
import { Avatar, Form, InputNumber, Popconfirm, Space, message } from 'antd';
import { useForm } from 'antd/es/form/Form';
import TextArea from 'antd/es/input/TextArea';
import React from 'react';

export interface IServiceProps {
	[key: string]: any;
}

const FILTER_CONDITION: IFilterParams = {
	keywords: '',
	currentPage: 1,
	pageSize: 10,
};
const Service: React.FC<IServiceProps> = () => {
	// 获取当前用户的身份信息
	const { initialState = {} } = useModel('@@initialState');
	const {
		userInfo: { city },
	} = initialState || {};

	const [isVisible, setIsVisible] = React.useState<boolean>(false); // 用于展示新增 modal 框的展示
	const [form] = useForm();
	const [editForm] = useForm();
	const [isEdit, setIsEdit] = React.useState<boolean>(false);
	const {
		loading,
		data,
		run: getListRun,
	} = useRequest((params) => getCurrent(params), {
		manual: true,
	});

	const [filterCondition, setFilterCondition] = React.useState<IFilterParams>(
		FILTER_CONDITION || {
			keywords: '',
			currentPage: 1,
			pageSize: 10,
		},
	);

	// 点击新增按钮
	const onHandleAdd = () => {
		form.resetFields();
		setIsVisible(true);
	};

	// 批量删除
	const onDelete = async (rowKeys: React.Key[], rows: Record<string, any>[]) => {
		try {
			const res = await deleted(rowKeys as number[]);
			if (res.status !== 200) {
				return message.error(res.message || '删除失败');
			}
			message.success('删除成功');
		} catch (error) {
			console.log('error', error);
		} finally {
			setFilterCondition({ ...FILTER_CONDITION });
		}
	};

	React.useEffect(() => {
		getListRun({ ...filterCondition, city });
	}, [filterCondition, city, getListRun]);

	const service_point = {
		机械维修: {
			text: '机械维修',
			status: 'Default',
		},
		'车身修复/喷漆': {
			text: '车身修复/喷漆',
			status: 'ok',
		},
		'油漆保护/车身包装': {
			text: '油漆保护/车身包装',
			status: 'Default',
		},
		'轮胎/轮毂': {
			text: '轮胎/轮毂',
			status: 'Default',
		},
		'空调/加热': {
			text: '空调/加热',
			status: 'Default',
		},
		保养: {
			text: '保养',
			status: 'Default',
		},
		'清洁/维护': {
			text: '清洁/维护',
			status: 'Default',
		},
		电气系统: {
			text: '电气系统',
			status: 'Default',
		},
		'电子设备/系统维修': {
			text: '电子设备/系统维修',
			status: 'Default',
		},
		'🔋 电池更换': {
			text: '电池更换',
			status: 'Default',
		},
	};

	// 页面table的数据
	const columns = [
		{
			title: '服务照片',
			key: 'photo',
			dataIndex: 'photo',
			render: (_, record: any) => (
				<Avatar
					alt="头像"
					size={60}
					style={{ verticalAlign: 'middle', border: '1px solid #f0f0f0' }}
					src={
						record.cover ? SERVICES + record.cover : SERVICES + '/vehicle/BiazfanxmamNRoxxVxka.png'
					}
				/>
			),
		},
		{
			title: '类别',
			key: 'category',
			dataIndex: 'category',
		},
		{
			title: '省',
			key: 'province',
			dataIndex: 'province',
		},
		{
			title: '城市',
			key: 'city',
			dataIndex: 'city',
		},
		{
			title: '服务点',
			key: 'service_point',
			dataIndex: 'service_point',
		},
		{
			title: '金额',
			key: 'money',
			dataIndex: 'money',
		},
		{
			title: '发布商家',
			key: 'shop',
			dataIndex: 'shop',
			render: (shop, _) => {
				return (
					<div>
						{shop?.name || '_'} <span>{shop?.role}</span>
					</div>
				);
			},
		},

		{
			title: '更新时间',
			key: 'updateDate',
			dataIndex: 'updated_date',
			render: (_, record) => <span>{record.updated_date && moment(record.updated_date).format('YYYY-MM-DD HH:mm:ss') || '-'}</span>,
		},
		{
			title: '操作',
			key: 'operator',
			render: (_, record: any) => {
				return (
					<Space size="middle">
						<a
							onClick={() => {
								history.push('/detail/' + record.id, record.type || 'user');
							}}
						>
							详情
						</a>
						<a
							onClick={() => {
								editForm.setFieldsValue(record);
								setIsEdit(true);
							}}
						>
							编辑
						</a>
						<Popconfirm
							title="删除"
							description="删除后不可恢复，是否确定删除?"
							placement="topRight"
							onConfirm={async () => {
								const res = await deleted([record.id]);
								if (res.status !== 200) {
									return message.error(res.message || '删除失败');
								}
								message.success('删除成功');
								setFilterCondition({ ...FILTER_CONDITION });
							}}
							okText="确定"
							cancelText="取消"
						>
							<a style={{ color: 'red' }}>删除</a>
						</Popconfirm>
					</Space>
				);
			},
		},
	];

	// 添加的表单项
	const editFormItems = [
		{
			title: '类型',
			dataIndex: 'category',
			width: 'm',
			valueEnum: {
				保养: {
					text: '保养',
					status: 'Default',
				},
				维修: {
					text: '维修',
					status: '维修',
				},
			},
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '省',
			dataIndex: 'province',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '市',
			dataIndex: 'city',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '商家',
			dataIndex: 'shopId',
			valueType: 'digit',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '店铺名称',
			dataIndex: 'shopNameId',
			valueType: 'string',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '服务金额',
			dataIndex: 'money',
			valueType: 'money',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '服务点',
			valueType: 'select',
			dataIndex: 'service_point',
			width: 'm',
			valueEnum: service_point,
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '服务描述',
			dataIndex: 'description',
			valueType: 'textarea',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
	];

	return (
		<div>
			<PageContainer>
				<CommonTable
					isAdd={false}
					isSticky
					loading={loading}
					columns={columns}
					total={data?.data?.total}
					dataSource={data?.data?.list}
					filterCondition={filterCondition}
					setFilter={setFilterCondition}
					isPagination={data?.total}
					onDelete={onDelete}
					isRowSelection
					onAdd={onHandleAdd}
				/>
			</PageContainer>

			{/* 弹窗 */}
			<FormCommon
				isOpen={isVisible}
				title="新增服务"
				layoutFormType="ModalForm"
				layout="horizontal"
				formInstance={form}
				setIsOpen={setIsVisible}
				width={400}
				onChange={async (values) => {
					const res = await add(values);
					if (res.status !== 200) {
						return message.error(res.message || '新增失败');
					}
					message.success('新增成功');
					setFilterCondition({ ...FILTER_CONDITION });
					setIsVisible(false);
				}}
				formColumn={editFormItems}
			/>

			{/* 编辑弹框 */}
			<DrawerForm
				form={editForm}
				onOpenChange={setIsEdit}
				title="编辑车辆基础信息"
				open={isEdit}
				onFinish={async (value) => {
					const res = await update(value);
					if (res.status !== 200) {
						return message.error(res.message || '更新失败');
					}
					message.success('更新成功');
					setFilterCondition({ ...FILTER_CONDITION });
					return true;
				}}
			>
				<ProForm.Group>
					<Form.Item name="photo">
						{/* <AvatarCom onChange={() => {}} /> */}
					</Form.Item>
				</ProForm.Group>

				<ProForm.Group>
					<ProFormText width="md" name="id" label="服务ID" disabled />
					<ProFormText width="md" name="primary_id" label="服务编号" disabled />
				</ProForm.Group>

				<ProForm.Group>
					<ProFormText width="md" name="category" label="类别" disabled />
					<ProFormText
						width="md"
						name="service_point"
						label="服务点"
						tooltip="最长为 10 位"
						placeholder="请输入昵称"
						rules={[
							{
								min: 0,
								max: 10,
							},
						]}
					/>
				</ProForm.Group>
				<ProForm.Group>
					<ProFormText width="md" name="province" label="省" placeholder="请输入名称" />
					<ProFormText width="md" name="city" label="市 " placeholder="请输入名称" />
				</ProForm.Group>
				<ProForm.Group>
					<Form.Item name="money" label="金额">
						<InputNumber />
					</Form.Item>
				</ProForm.Group>
				<Form.Item name="description" label="服务描述">
					<TextArea placeholder="用一句话形容自己吧" showCount maxLength={100} />
				</Form.Item>
			</DrawerForm>
		</div>
	);
};

export default Service;
